package com.lucker.service.wechat;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.lucker.common.util.HttpUtil;
import com.lucker.service.wechat.model.WeChatToken;
import com.lucker.service.wechat.model.WeChatUserInfo;

@Service
public class WeChatServiceImpl implements WeChatService {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public WeChatToken getWeChatToken(String code) {
		//获取token 第一步
        StringBuffer URL = new StringBuffer();
        URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=").append("wechat.appId").append("&secret=").append("wechat.secret").append("&code=").append(code).append("&grant_type=authorization_code");
        String json = null;
        try{
        	json = HttpUtil.get(URL.toString());
        }catch (Exception e) {
        	logger.error("请求微信token错误 ",e);
        	return null;
		}
        
        WeChatToken vo = JSONObject.parseObject(json, WeChatToken.class);
        if (vo.getErrmsg() != null) {
        	logger.error("请求微信token错误  错误码 : {} , 错误信息: {}", vo.getErrmsg());
        	return null;
        }
		return vo;
	}

	@Override
	public WeChatUserInfo getWeChatUserInfo(String openId) {
		
		 //第二步 拉取用户信息
        StringBuffer URL1 = new StringBuffer();
        URL1.append("https://api.weixin.qq.com/sns/userinfo?access_token=").append("token").append("&openid=").append("openid").append("&lang=zh_CN");
        String json = null;
        try {
        	HttpUtil.get(URL1.toString());
        }catch(IOException e) {
        	logger.error("请求微信用户信息发生网络错误 {}",e);
        	return null;
        	
        }catch(Exception e) {
        	logger.error("请求微信用户信息错误 ",e);
        	return null;
        }
        WeChatUserInfo vo = JSONObject.parseObject(json, WeChatUserInfo.class);
        //如果拉取失败就刷新
        if (vo.getErrmsg() != null) {
        	logger.error("请求微信用户信息错误  错误码 : {} , 错误信息: {}", vo.getErrmsg());
        	return null;                 
        }
		return vo;
	}
	
	
	
	

}
